import * as crypto from 'node:crypto';

/**
 * MD5加密
 * @param str 要加密的字符串
 * @returns 加密后的字符串
 */
export function md5(str: string): string {
  const hash = crypto.createHash('md5');
  hash.update(str);
  return hash.digest('hex').toString();
}

/**
 * 密码加盐加密
 * @param password
 * @returns 加密后的密码和盐
 */
export function encryptPassword(password: string): {
  salt: string;
  hash: string;
} {
  const salt = crypto.randomBytes(16).toString('hex');
  const hash = crypto
    .pbkdf2Sync(password, salt, 1000, 64, 'sha512')
    .toString('hex');
  return { hash, salt };
}

/**
 * 验证密码
 * @param password 密码
 * @param hash 密码哈希
 * @param salt 数据库中的盐
 * @returns Boolean
 */
export function validatePassword(
  password: string,
  hash: string,
  salt: string,
): boolean {
  const verifyHash = crypto
    .pbkdf2Sync(password, salt, 1000, 64, 'sha512')
    .toString('hex');
  return hash === verifyHash;
}

/**
 * 格式化日期
 * @param date 日期对象
 * @param format 格式化模板
 * @returns 格式化后的日期字符串
 */
export function formatDate(
  date: Date,
  format: string = 'YYYY-MM-DD HH:mm:ss',
): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds);
}
